<?php

class DBU_Db_Adapters_MySQLI extends DBU_Db_Adapters_Abstract implements DBU_Db_Adapters_Interface {

	protected $connection;

	/**
	 * Connects to MySQLI server
	 *
	 * @param string $host
	 * @param string $user
	 * @param string $password
	 * @param string $database
	 * @return resource
	 */
	public function connect($host = false, $user = false, $password = false, $database = false) {
		$this->connection = new mysqli($host, $user, $password, $database);
		
		if (mysqli_connect_errno()) {
			throw new DBU_Db_Exception(mysqli_connect_error());
		}		

		return $this->connection;
	}


   /**
	* Executes SQL query
	*
	* @param string $sql
	* @return result ID
	*/
	public function query($sql) {
		return $this->connection->query($sql);
	}


	public function lastInsertID() {
		return $this->connection->insert_id;
	}


	public function affectedRows() {
		return $this->connection->affected_rows;
	}


	public function info() {
		return $this->connection->info;
	}


	public function numRows($result) {
		return $result->num_rows;
	}


	public function fetchArray($result) {
		return $result->fetch_array();
	}


	public function fetchAssoc($result) {
		return $result->fetch_assoc();
	}


	public function fetchObject($result) {
		return $result->fetch_object();
	}


	public function result($result, $row, $field) {
		return mysqli_result($result, $row, $field);
	}


	/**
	 * Dumy method
	 * TODO: check if mysqli has a free result 
	 * @param unknown_type $result	 
	 */
	public function freeResults($result) {
		return true;
	}

	public function describeTable($table) {
		$return = array();
		$result = $this->execute('DESCRIBE ' . $table);

		if (mysqli_num_rows($result)) {
			while ($row = $this->fetchAssoc($result)) {
				$return[$row['Field']] = array(
					'field'             => $row['Field'],
					'type'              => $row['Type'],
					'primary'           => ($row['Key'] == 'PRI'),
					'default'           => $row['Default'],
					'auto_increment'    => ($row['Extra'] == 'auto_increment')
					);
			}
		}
		return $return;
	}


    public function cleanData($data) {
        return $this->connection->real_escape_string($data);
    }

    
    public function error() {
    	return $this->connection->error;
    }
    

	public function disconnect() {
		$this->connection->close();
	}
}